package com.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.dto.weixiubaoyang.*;
import com.example.entity.mysql.MoldAllocationDetail;
import com.example.entity.mysql.MoldAllocationHeader;
import com.example.entity.mysql.Resource;
import com.example.exception.CustomException;
import com.example.mapper.MoldAllocationDetailMapper;
import com.example.mapper.MoldAllocationHeaderMapper;
import com.example.mapper.pc.ResourceMapper;
import com.example.service.MoldAllocationDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.untils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-11-27
 */
@Service
@Slf4j
public class MoldAllocationDetailServiceImpl extends ServiceImpl<MoldAllocationDetailMapper, MoldAllocationDetail> implements MoldAllocationDetailService {
    @Autowired
    private MoldAllocationHeaderMapper moldAllocationHeaderMapper;
    @Autowired
    private MoldAllocationDetailMapper moldAllocationDetailMapper;
    @Autowired
    private ResourceMapper resourceMapper;

    private static String ORDER_TYPE = "MT";

    @DSTransactional
    @Override
    public String addMoldAllocation(MoldAllocationAddDto moldAllocationAddDto) {
        moldAllocationAddDto.setApplicationDate(StringUtils.ifEmptySet(moldAllocationAddDto.getApplicationDate()
                ,LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        MoldAllocationHeader moldAllocationHeader = new MoldAllocationHeader();
        BeanUtils.copyProperties(moldAllocationAddDto, moldAllocationHeader);
        //单别
        moldAllocationHeader.setOrderType(ORDER_TYPE);
        //开始获取单号
        //获取日期前缀
        DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentTime = LocalDateTime.now().format(yyyyMM);

        //获取今天插入的数量
        Integer sum=moldAllocationHeaderMapper.getNowXjNum(currentTime)+1;
        log.info("sum"+sum);
        String orderNumber=currentTime+String.format("%03d",sum);
        moldAllocationHeader.setOrderNumber(orderNumber);
        moldAllocationHeader.setCompletionCode("N");
        moldAllocationHeader.setApprovalCode("N");
        moldAllocationHeader.setApplicationDate(
                moldAllocationAddDto.getApplicationDate().replaceAll("-","")
        );
        //状态默认未审核
        moldAllocationHeader.setStatus("N");
        moldAllocationHeaderMapper.insert(moldAllocationHeader);

        if (moldAllocationAddDto.getMoldAllocationDetailList()!=null){
            for (MoldAlloxationAddDetailDto detail: moldAllocationAddDto.getMoldAllocationDetailList()) {
                //查找单身表中单别单号相同的数量，添加时加入序号
                LambdaQueryWrapper<MoldAllocationDetail> wrapper1=new LambdaQueryWrapper<>();
                wrapper1.eq(MoldAllocationDetail::getOrderNumber,orderNumber)
                        .eq(MoldAllocationDetail::getOrderType,ORDER_TYPE);

                //如果在设备在单身表中已经有了，就不能添加，得结束上一张单子
                //TODO 需要判断模具是否还在本地的字段
//            LambdaQueryWrapper<MoldAllocationDetail> wrapper=new LambdaQueryWrapper<>();
//            wrapper.eq(MoldAllocationDetail::getDeviceId,detail.getDeviceId())
//                    .eq(MoldAllocationDetail::getCompletionCode,"N");
//            Integer count=moldAllocationDetailMapper.selectCount(wrapper);
//            if (count!=0){
//                throw new RuntimeException("模具已经调拨，请结束上一张单子");
//            }
                //插入单身
                MoldAllocationDetail moldAllocationDetail = new MoldAllocationDetail();
                BeanUtils.copyProperties(detail, moldAllocationDetail);

                if (detail.getDeviceId()==null){
                    throw new CustomException("500","模具编号为空");
                }
                //获取原地址
                Resource one =resourceMapper.selectOneByDeviceId(detail.getDeviceId());
                //放入原地址，审核吗，结束码，和序号
                log.info(one.getStorageLocation());
                moldAllocationDetail.setOriginalLocation(one.getStorageLocation());
                moldAllocationDetail.setProposedLocation(one.getOwnerName());
                moldAllocationDetail.setCompletionCode("N");
                moldAllocationDetail.setApprovalCode("N");
                //单身的单别和单号
                moldAllocationDetail.setOrderType(ORDER_TYPE);
                //单号=年月日+顺序号
                moldAllocationDetail.setOrderNumber(orderNumber);
                try {
                    moldAllocationDetailMapper.insert(moldAllocationDetail);
                } catch (DuplicateKeyException e) {
                    throw new CustomException("500","不能传入两个相同的模具!");
                }
            }
        }
        return "保存成功";
    }

    @Override
    @DSTransactional
    public String updateMoldAllocation(MoldAllocationUpdateDto dto) {
        MoldAllocationHeader header = moldAllocationHeaderMapper.selectOne(
                new LambdaQueryWrapper<MoldAllocationHeader>().eq(MoldAllocationHeader::getOrderType, ORDER_TYPE)
                        .eq(MoldAllocationHeader::getOrderNumber, dto.getOrderNumber())
        );
        if (header==null) throw new CustomException("500","不存在的单号");
        if (!header.getStatus().equals("N")) throw new CustomException("500","当前调拨单状态无法修改!");
        MoldAllocationHeader moldAllocationHeader = new MoldAllocationHeader();
        BeanUtils.copyProperties(dto, moldAllocationHeader);
        moldAllocationHeaderMapper.update(moldAllocationHeader,
                new LambdaQueryWrapper<MoldAllocationHeader>()
                        .eq(MoldAllocationHeader::getOrderType, moldAllocationHeader.getOrderType())
                        .eq(MoldAllocationHeader::getOrderNumber, moldAllocationHeader.getOrderNumber()));
        //修改单身有可能新增,直接删除原来的，将新的填充进去
        if (dto.getMoldAllocationDetailList()!=null){
            this.lambdaUpdate().eq(MoldAllocationDetail::getOrderType,moldAllocationHeader.getOrderType())
                    .eq(MoldAllocationDetail::getOrderNumber,moldAllocationHeader.getOrderNumber()).remove();
            for (MoldAlloxationUpdateDetailDto detailDto : dto.getMoldAllocationDetailList()) {
                MoldAllocationDetail detail=new MoldAllocationDetail();
                BeanUtils.copyProperties(detailDto, detail);
                detail.setOrderType(ORDER_TYPE);
                detail.setOrderNumber(moldAllocationHeader.getOrderNumber());

                Resource one =resourceMapper.selectOneByDeviceId(detailDto.getDeviceId());
                //放入原地址，审核吗，结束码，和序号
                log.info(one.getStorageLocation());
                detail.setOriginalLocation(one.getStorageLocation());
                detail.setCompletionCode("N");
                detail.setApprovalCode("N");
                try {
                    moldAllocationDetailMapper.insert(detail);
                } catch (DuplicateKeyException e) {
                    throw new CustomException("500","不能传入两个相同的模具!");
                }
            }
        }
        return "修改成功";
    }

    @Override
    public String deleteMold(Integer id) {
        if (moldAllocationDetailMapper.selectById(id)==null)
            throw new CustomException("500","不存在的信息");
        return moldAllocationDetailMapper.deleteById(id)>0 ? "删除成功":"删除失败";
    }

    //更新调拨单身
    @Override
    public String updateMoldAllocationDetail(MoldApplyDto moldApplyDto) {
//       //查询该条单身数据
//        LambdaQueryWrapper<MoldAllocationDetail> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(MoldAllocationDetail::getId, moldApplyDto.getId())
//                .eq(MoldAllocationDetail::getOrderType, moldApplyDto.getOrderType())
//                .eq(MoldAllocationDetail::getOrderNumber, moldApplyDto.getOrderNumber());
//        MoldAllocationDetail exist = moldAllocationDetailMapper.selectOne(wrapper);
//        if (exist.getCompletionCode().equals("Y")||exist.getCompletionCode().equals("V")){
//            throw new RuntimeException("该条数据已经结束，不能修改");
//        }
//        //改变单身数据
//        Integer num = moldAllocationDetailMapper.updateCode(moldApplyDto);
//
//        Integer num2=0;
//        if (moldApplyDto.getApprovalCode().equals("Y")){
//            //改变原有地址
//            num2 = resourceMapper.updateStorageLocation(exist);
//        }
//
//        LambdaQueryWrapper<MoldAllocationDetail> wrapper1 = new LambdaQueryWrapper<>();
//        wrapper1.eq(MoldAllocationDetail::getOrderNumber, moldApplyDto.getOrderNumber())
//                .eq(MoldAllocationDetail::getOrderType, moldApplyDto.getOrderType())
//                .eq(MoldAllocationDetail::getCompletionCode, "N");
//        int fullnum = moldAllocationDetailMapper.selectCount(wrapper1);
//        //如果次单头没有需要改的单子了，更改单头审核状态
//        if (fullnum==0){
//            moldApplyDto.setApprovalCode("Y");
//            moldAllocationHeaderMapper.updateCode(moldApplyDto);
//        }
//        return "更新单身"+num+"跟新资源地址"+num2;
        return null;
    }
}
